package handler

import (
	"encoding/json"
	"order-pro/cache"
	"order-pro/model"
	"order-pro/pkg"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}

	redis_login_key := "redis_login_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()

	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "错误三次",
		})
		return
	}

	var user model.User

	err := model.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账号或密码错误",
		})
		return
	}

	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return

	}

	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 0 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "错误三次，封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return

}

func RoleNodAdd(c *gin.Context) {

	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))

	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}

	model.DB.Create(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return

}

func UserRole(c *gin.Context) {

	uid := c.Query("uid")
	var data []model.Role

	/*
			SELECT
		  *
		FROM
		  roles
		  LEFT JOIN user_roles ON user_roles.rid = roles.id
		WHERE
		  user_roles.uid = 1
	*/

	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON user_roles.rid = roles.id").
		Where("user_roles.uid = ?", uid).
		Debug().Find(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return

}

func RoleNode(c *gin.Context) {

	rid := c.Query("rid")
	var data []model.Node

	/*
				SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes ON role_nodes.nid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/

	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid = nodes.id").
		Where("role_nodes.rid = ?", rid).
		Debug().Find(&data)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": data,
	})
	return

}

func ShopAdd(c *gin.Context) {

	shopNo := c.PostForm("shop_no")
	shopName := c.PostForm("shop_name")

	data := model.Shop{
		ShopNo:   shopNo,
		ShopName: shopName,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return

}

func OrderAdd(c *gin.Context) {

	orderNo := c.PostForm("order_no")
	orderPrice := c.PostForm("order_price")
	sid, _ := strconv.Atoi(c.PostForm("sid"))

	data := model.Order{
		OrderNo:    orderNo,
		OrderPrice: orderPrice,
		Sid:        sid,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return

}

func OrderList(c *gin.Context) {

	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var data []model.OrderList

	/*
		SELECT
		  orders.id AS ID,
		  orders.order_no AS OrderNo,
		  orders.order_price AS OrderPrice,
		  shops.shop_no AS ShopNo,
		  shops.shop_name AS ShopName
		FROM
		  orders
		  LEFT JOIN shops ON orders.sid = shops.id
	*/

	redis_list_key := "redis_list_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		model.DB.Table("orders").
			Select(
				"orders.id AS ID",
				"orders.order_no AS OrderNo",
				"orders.order_price AS OrderPrice",
				"shops.shop_no AS ShopNo",
				"shops.shop_name AS ShopName",
			).
			Joins("LEFT JOIN shops ON orders.sid = shops.id").
			Offset(offset).Limit(size).
			Debug().Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}

	var total int64
	model.DB.Model(&model.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表成功",
		"data":  data,
		"total": total,
	})
	return

}

func OrderDetail(c *gin.Context) {
	id := c.Query("id")

	var data model.Order

	redis_detail_key := "redis_detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()

	if result == "" {
		model.DB.Where("id = ?", id).First(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": data,
	})
	return

}
